package org.jspar.expr;


public class BinaryExpr extends Expr {

	public static final int MULTIPLY = 1;
	public static final int DIVIDE = 2;
	public static final int ADD = 3;
	public static final int SUBSTRACT = 4;

	private int op;
	private Expr left;
	private Expr right;

	public BinaryExpr(int op, Expr left, Expr right) {
		this.op = op;
		this.left = left;
		this.right = right;
	}

	public Expr reduce() {
		Expr vt = left.reduce();
		switch (op) {
		case ADD:
			return vt.add(right);
		case SUBSTRACT:
			return vt.substract(right);
		case MULTIPLY:
			return vt.multiply(right);
		case DIVIDE:
			return vt.divide(right);
		}
		throw new RuntimeException("bad operator");
	}

	public int eval() {
		switch (op) {
		case ADD:
			return left.eval() + right.eval();
		case SUBSTRACT:
			return left.eval() - right.eval();
		case MULTIPLY:
			return left.eval() * right.eval();
		case DIVIDE:
			return left.eval() / right.eval();
		}
		throw new RuntimeException("bad operator");
	}

	public Expr add(Expr a) {
		return new BinaryExpr(op, left.add(a), right.add(a));
	}

	public Expr substract(Expr a) {
		return new BinaryExpr(op, left.substract(a), right.substract(a));
	}

	public Expr multiply(Expr a) {
		return new BinaryExpr(op, left.multiply(a), right.multiply(a));
	}

	public Expr divide(Expr a)  {
		return new BinaryExpr(op, left.divide(a), right.divide(a));
	}
}
